<template>
    <div class="app-container">
    
        <div class="filter-container add1">
    
            <el-form style="">
    
                <el-form-item>
    
                    <!-- 按钮级别的控制,使用hasPerm来判断是否应该有添加这个按钮 -->
    
                    <el-button type="primary" icon="plus" size="medium" @click="showCreate" v-if="hasPerm('article:add')">添加
    
                    </el-button>
    
                    <!-- 下载模板 -->
                    <a href="/src/views/purchase/2019416.xlsx">
                        <el-button type="success" size="medium" icon="plus" v-if="hasPerm('article:add')">下载导入模板
                        </el-button>
                    </a>
                     <!-- 后端导入 -->
                    <el-upload
                        :show-file-list="false"
                        accept="application/vnd.ms-excel"
                        :action="uploadUrl()"
                        :on-success="fileUploadSuccess"
                        :on-error="fileUploadError" 
                        :disabled="fileUploadBtnText=='正在导入'"
                        :before-upload="beforeFileUpload" style="display: inline">
                        <el-button size="medium" type="success" :loading="fileUploadBtnText=='正在导入'"><i class="fa fa-lg fa-level-up" style="margin-right: 5px"></i>{{fileUploadBtnText}}
                        </el-button>
                    </el-upload>

                    <el-button @click="exportExcelOpertor" type="primary" size="medium" icon="plus" v-if="hasPerm('article:add')">前台导出</el-button>
                    <!-- <el-button @click="exportExcelByback" type="primary" size="medium" icon="plus" v-if="hasPerm('article:add')">后台导出</el-button> -->
                    <el-button @click="showDisplay" type="info" size="medium" icon="plus">显示字段</el-button>
                    <!-- <el-button @click="exportExcel" type="primary" icon="plus" v-if="hasPerm('article:add')" >导出</el-button> -->
                    <el-button type="danger" size="medium" v-if="multipleSelectionFlag" @click="delSelect">    
                        批量删除    
                    </el-button>
                        <el-button type="primary" size="medium" icon="plus" @click="showUserInfo" v-if="hasPerm('article:add')">获得该用户信息    
                    </el-button>
                     <!-- 后端导入 -->
                    <el-upload
                        :show-file-list="false"
                        accept="application/vnd.ms-excel"
                        :action="uploadUrlDingdan()"
                        :on-success="fileUploadSuccess"
                        :on-error="fileUploadError" 
                        :disabled="fileUploadBtnText=='正在导入'"
                        :before-upload="beforeFileUpload" style="display: inline">
                        <el-button size="medium" type="success" :loading="fileUploadBtnText=='正在导入'"><i class="fa fa-lg fa-level-up" style="margin-right: 5px"></i>{{fileUploadBtnText}}
                        </el-button>
                    </el-upload>    
                </el-form-item>    
            </el-form>   
        </div>
    
        <div class="searchWord">    
            <!-- style="display: inline-block;"  -->    
            <el-input v-model="search" placeholder="请输入搜索内容" @input="inputFunction()">    
            </el-input>    
        </div>    
        <br>
    
        <el-table class="tabless" :data="list" v-loading.body="listLoading" element-loading-text="拼命加载中" border fit highlight-current-row :row-class-name="tableRowClassName" @sort-change='sortChange' @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" v-if="displayAttribute.select">    
            </el-table-column>    
            <el-table-column align="center" label="序号" width="80" v-if="displayAttribute.id">    
                <template slot-scope="scope">    
              <!-- 采购订单的索引 -->    
              <span v-text="getIndex(scope.$index)"> </span>    
              <!-- 采购订单的id -->    
              <!-- <span v-text="scope.row.id"> </span> -->
    </template>
      </el-table-column>

      <el-table-column align="center" prop="parentId" label="订单号" style="width: 60px;" v-if="displayAttribute.purchase_id"></el-table-column>
      <el-table-column align="center" prop="purchaseStatus" label="订单状态" style="width: 60px;" v-if="displayAttribute.status"></el-table-column>
      <el-table-column align="center" prop="applyId" label="申请单号" style="width: 60px;" v-if="displayAttribute.application_id"></el-table-column>
      <el-table-column align="center" prop="supplierName" label="供应商" style="width: 60px;" v-if="displayAttribute.supplier_name"></el-table-column>
      <el-table-column align="center" prop="supplierContact" label="联系人" style="width: 60px;" v-if="displayAttribute.supplier_contact"></el-table-column>
      <el-table-column align="center" prop="supplierTel" label="电话" style="width: 60px;" v-if="displayAttribute.supplier_phone"></el-table-column>
      <el-table-column align="center" prop="supplierEmail" label="邮箱" style="width: 60px;" v-if="displayAttribute.supplier_email"></el-table-column>
      <el-table-column align="center" prop="supplierFax" label="传真" style="width: 60px;" v-if="displayAttribute.supplier_fax"></el-table-column>
      <el-table-column align="center" prop="applyTime" label="申请日期" style="width: 60px;" v-if="displayAttribute.order_time"></el-table-column>
      <el-table-column align="center" prop="requireTime" label="要货日期" style="width: 60px;" v-if="displayAttribute.required_time"></el-table-column>
      <el-table-column align="center" prop="mark" label="备注" style="width: 60px;" v-if="displayAttribute.remark"></el-table-column>

      <el-table-column align="center" label="管理" width="300" v-if="hasPerm('article:update') & displayAttribute.manageMent">

    <template slot-scope="scope">
        <el-button type="primary" @click="checkOrder(scope.$index, scope.row)" v-if="list[scope.$index].purchaseStatus == '待审核'">审核</el-button>
        <el-button type="primary" @click="finishOrder(scope.$index, scope.row)" v-if="list[scope.$index].purchaseStatus == '审核通过'" :disabled = "enableFinishAndSuspend">完成</el-button>
        <el-button type="primary" @click="suspendOrder(scope.$index, scope.row)" v-if="list[scope.$index].purchaseStatus == '审核通过'" :disabled = "enableFinishAndSuspend">中止</el-button>
        <el-button type="primary" @click="inwarehouse(scope.$index, scope.row)" v-if="list[scope.$index].purchaseStatus == '待入库'" :disabled = "enableStocking">入库</el-button>
        <el-button type="primary" icon="edit" @click="showDetails(scope.$index)" :disabled = "enableItemShowDetails">详情</el-button> 
        <el-button type="primary" icon="edit" @click="showUpdate(scope.$index)" v-if="list[scope.$index].purchaseStatus == '待审核'" :disabled = "enableItemEdit">修改</el-button>
        <el-button type="danger" @click="handleDelete(scope.$index, scope.row)" v-if="list[scope.$index].purchaseStatus == '待审核'" :disabled = "enableItemDelete">删除</el-button>
    </template>

<!-- <template slot-scope="scope">
    <el-button type="primary" icon="edit" @click="showDetails(scope.$index)">详情</el-button>
    <el-button type="primary" icon="edit" @click="showUpdate(scope.$index)">修改</el-button>    
    <el-button type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
</template> -->
      </el-table-column>
    </el-table>
    <!-- 删除提示框 -->
        <el-dialog title="提示" :visible.sync="delVisible" width="300px" center>
            <div class="del-dialog-cnt">删除不可恢复，是否确定删除？</div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="delVisible = false">取 消</el-button>
                <el-button type="primary" @click="deleteRow" >确 定</el-button>
            </span>
        </el-dialog>

        <!-- 删除提示框 -->
        <el-dialog title="提示" :visible.sync="delVisibleByBatch" width="300px" center>
            <div class="del-dialog-cnt">删除不可恢复，是否确定批量删除？</div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="delVisibleByBatch = false">取 消</el-button>
                <el-button type="primary" @click="delAll" >确 定</el-button>
            </span>
        </el-dialog>
    
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="listQuery.pageNum" 
      :page-size="listQuery.pageRow"
      :total="totalCount"
      :page-sizes="[3, 20, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper"
      class="pagination">
    </el-pagination>

    <!-- 添加/更新弹出框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <!-- <el-form class="small-space" :model="tempPurchase" label-position="left" label-width="150px">
      <el-row class="infor_bg">
        <el-col :span="12">
        <el-form-item label="采购订单" v-if="dialogStatus=='create' | dialogStatus=='update'">
          <el-input type="text" v-model="tempPurchase.content" @keyup.native = "handlerPurchase">
          </el-input>
          <el-tag type="danger" v-if="this.displayInfoFromBack">{{infoFromBack}}</el-tag>          
        </el-form-item> -->

    <el-form class="small-space" :model="purchaseOrder" ref="dynamicValidateOligo" :rules="rules" v-loading.body="listLoading" label-order="left" label-width="120px" >
      <el-row class="infor_bg">
        <!-- 左侧列 -->
        <el-col :span="12">
          <el-form-item label="部门" prop="department_name" v-if="dialogStatus=='create' | dialogStatus=='update'" :required="true">
            <!-- <el-input type="text" v-model="purchaseOrder.department_name" style='width:300px;'></el-input> -->
            <el-autocomplete class="inline-input" placeholder="请搜索并选择" v-model="purchaseOrder.department_name" :fetch-suggestions="departmentQuerySearch" @select="handleDepartmentSelect"></el-autocomplete>
          </el-form-item>
          <el-form-item label="发件人" prop="staff_name" v-if="dialogStatus=='create' | dialogStatus=='update'" :required="true">
            <el-autocomplete class="inline-input" placeholder="请搜索并选择" v-model="purchaseOrder.staff_name_combine" :fetch-suggestions="staffQuerySearch" @select="handleStaffSelect"></el-autocomplete>
            <!-- <el-input type="text" v-model="purchaseOrder.staff_name" style='width:300px;'></el-input> -->
          </el-form-item>
          <el-form-item label="供应商" prop="supplier_name" v-if="dialogStatus=='create' | dialogStatus=='update'" :required="true">
            <el-autocomplete class="inline-input" placeholder="请搜索并选择，或添加新供应商" style='width:300px;' v-model="purchaseOrder.supplier_name" :fetch-suggestions="companyQuerySearch" @select="handleCompanySelect"></el-autocomplete>
            <!-- <el-input type="text" v-model="purchaseOrder.supplier_name" style='width:300px;'></el-input> -->
          </el-form-item>
          <el-form-item label="电子邮箱" prop="supplier_email" v-if="dialogStatus=='create' | dialogStatus=='update'" :required="false">
            <el-input type="text" v-model="purchaseOrder.supplier_email" style='width:300px;'></el-input>
          </el-form-item>
          <el-form-item label="传真" prop="supplier_fax" v-if="dialogStatus=='create' | dialogStatus=='update'" :required="false">
            <el-input type="text" v-model="purchaseOrder.supplier_fax" style='width:300px;'></el-input>
          </el-form-item>
          <el-form-item label="订购日期" prop="order_time_tmp" :editable="false" readonly="true" v-if="dialogStatus=='create' | dialogStatus=='update'" :required="true">
            <el-date-picker v-model="purchaseOrder.order_time_tmp" type="datetime" placeholder="选择日期时间" align="right" :picker-options="pickerOptions" style='width:300px;'>
            </el-date-picker>
          </el-form-item>

        </el-col>

        <!-- 右侧列 -->
        <el-col :span="12">          
          <el-form-item label="申请单号" prop="apply_id" v-if="dialogStatus=='create' | dialogStatus=='update'" :required="true">
            <el-input type="text" v-model="purchaseOrder.apply_id" style='width:300px;'></el-input>
          </el-form-item>
          <el-form-item label="订单号" prop="purchase_id" v-if="dialogStatus=='create' | dialogStatus=='update'" :required="true">
            <el-input type="text" v-model="purchaseOrder.purchase_id" style='width:300px;'></el-input>
          </el-form-item>
          <el-form-item label="联系人" prop="supplier_contact" v-if="dialogStatus=='create' | dialogStatus=='update'" :required="true">
            <el-input type="text" v-model="purchaseOrder.supplier_contact" style='width:300px;'></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="supplier_phone" v-if="dialogStatus=='create' | dialogStatus=='update'" :required="true">
            <el-input type="text" v-model="purchaseOrder.supplier_phone" style='width:300px;'></el-input>
          </el-form-item>
          <el-form-item label="要货日期" prop="required_time_tmp" :editable="false" readonly="true" v-if="dialogStatus=='create' | dialogStatus=='update'" :required="true">
            <el-date-picker v-model="purchaseOrder.required_time_tmp" type="datetime" placeholder="选择日期时间" align="right" :picker-options="pickerOptions" style='width:300px;'>
            </el-date-picker>
          </el-form-item>
            <el-form-item label="价格合计（元）" prop="sum" readonly="true" v-if="dialogStatus=='create' | dialogStatus=='update'" :required="false">
              <el-input type="text" v-model="purchaseOrder.sum" placeholder="0.00" style='width:300px;' readonly="true"></el-input>
            </el-form-item>
        </el-col>
        </el-row>
        <br>
        
        <el-table :data="purchaseOrder.tableDatas" style="width: 100%" max-height="200" height="200" stripe border @selection-change="subTableHandleSelectionChange" v-if="dialogStatus=='create' | dialogStatus=='update'">
          <el-table-column type="selection" width="55" align="center"></el-table-column>

          <el-table-column prop="product_id"  label="编号" width="100" align="center">
            <template slot-scope="scope">
              <div
                  :prop="'tableDatas.' + scope.$index + '.product_id'">
                  <el-input type="text"  v-model="scope.row.product_id"></el-input>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="product_name" label="货物名称" width="200" align="center">
            <template slot-scope="scope">
              <div
                  :prop="'tableDatas.' + scope.$index + '.product_name'">
                  <!-- <el-input type="text"  v-model="scope.row.product_name" :maxlength="35"></el-input> -->
                  <el-autocomplete class="inline-input" placeholder="请搜索并选择" v-model="scope.row.product_name" :fetch-suggestions="productQuerySearch" @select="((item)=>handleProductSelect(item, scope.$index, scope.row))"></el-autocomplete>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="product_type" label="货号" width="120" align="center">
            <template slot-scope="scope">
            <div
                :prop="'tableDatas.' + scope.$index + '.product_type'">
                <el-input type="text"  v-model="scope.row.product_type"></el-input>
            </div>
            </template>
          </el-table-column>

          <el-table-column prop="quantity" label="数量" width="80" align="center">
            <template slot-scope="scope">
                <div
                  :prop="'tableDatas.' + scope.$index + '.quantity'">
                  <el-input type="text"  v-model="scope.row.quantity" @change = "handlerComputeSum(scope.$index, scope.row)"></el-input>
                </div>
            </template>
          </el-table-column>

          <el-table-column prop="unit" label="单位" width="80" align="center">
            <template slot-scope="scope">
                <div
                  :prop="'tableDatas.' + scope.$index + '.unit'">
                  <el-input type="text"  v-model="scope.row.unit"></el-input>
                  <!-- <el-autocomplete class="inline-input" placeholder="请搜索并选择" v-model="scope.row.unit" :fetch-suggestions="unitQuerySearch" @select="handleUnitSelect"></el-autocomplete> -->
                </div>
            </template>
          </el-table-column>

          <el-table-column prop="unit_price" label="单价/元" width="80" align="center">
            <template slot-scope="scope">
                <div
                  :prop="'tableDatas.' + scope.$index + '.unit_price'">
                  <el-input type="text"  v-model="scope.row.unit_price" @change = "handlerComputeSum(scope.$index, scope.row)"></el-input>
                </div>
            </template>
          </el-table-column>

          <el-table-column prop="total_price" label="总价/元" width="80" align="center">
            <template slot-scope="scope">
              <div
                  :prop="'tableDatas.' + scope.$index + '.total_price'">
                  <el-input type="text"  v-model="scope.row.total_price" readonly="true"></el-input>
                </div>
            </template>
          </el-table-column>

          <el-table-column prop="remark" label="备注" width="100" align="center">
            <template slot-scope="scope">
              <div
                  :prop="'tableDatas.' + scope.$index + '.remark'">
                  <el-input type="text"  v-model="scope.row.remark"></el-input>
                </div>
            </template>
          </el-table-column>
        </el-table>

        <div align="center" v-if="dialogStatus=='create' | dialogStatus=='update'">
            <br>
            <el-button size="small" type="primary" @click="addRecord"> 添加行 </el-button>
            <el-button size="small" type="primary" @click="deleteRecord" :disabled = "enableDelete"> 删除行 </el-button>
            <br>
        </div>

 
        <div v-if="dialogStatus=='dispalyAtt'">
          <el-checkbox v-model="displayAttribute.select">复选框</el-checkbox><br>
          <el-checkbox v-model="displayAttribute.id">序号</el-checkbox><br>
          <el-checkbox v-model="displayAttribute.purchase_id">订单号</el-checkbox><br>
          <el-checkbox v-model="displayAttribute.status">订单状态</el-checkbox><br>          
          <!-- <el-checkbox v-model="displayAttribute.son_order_id">子订单号</el-checkbox><br> -->
          <el-checkbox v-model="displayAttribute.application_id">申请单号</el-checkbox><br>
          <el-checkbox v-model="displayAttribute.supplier_name">供应商</el-checkbox><br>
          <el-checkbox v-model="displayAttribute.supplier_contact">联系人</el-checkbox><br>
          <el-checkbox v-model="displayAttribute.supplier_phone">电话</el-checkbox><br>
          <el-checkbox v-model="displayAttribute.supplier_email">邮箱</el-checkbox><br>
          <el-checkbox v-model="displayAttribute.supplier_fax">传真</el-checkbox><br>
          <el-checkbox v-model="displayAttribute.order_time">申请日期</el-checkbox> <br>
          <el-checkbox v-model="displayAttribute.required_time">要货日期</el-checkbox>
          <el-checkbox v-model="displayAttribute.remark">备注</el-checkbox>
          <el-checkbox v-model="displayAttribute.manageMent">管理</el-checkbox>
        </div>
      </el-form>


      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="success" @click="createPurchase" :disabled = "enableCreate">创 建</el-button>
        <el-button type="primary" v-if="dialogStatus=='update'" @click="updatePurchase" :disabled = "enableUpdate">修 改</el-button>
        
      </div>
    </el-dialog>

    <!-- 订单状态改变确认提示框 -->
    <!-- 采购订单审核（通过-不通过） -->
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible1"
      width="30%"
      >
      <el-radio v-model="radio2" label="1">同意</el-radio>
      <el-radio v-model="radio2" label="2">拒绝</el-radio>
      <br><br>
      理由：
      <el-input
        type="textarea"
        :rows="3"
        placeholder="请输入审核理由"
        v-model="textarea2">
      </el-input>

      <span slot="footer">
        <el-button @click="dialogFormVisible1 = false">取 消</el-button>
        <el-button type="primary" @click="checkOrderSubmit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 是否完成采购订单 -->   
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible2"
      width="30%"
      @close="dialogFormVisible2 = false">
      您确定完成采购订单?
      <span slot="footer">
        <el-button @click="dialogFormVisible2 = false">取 消</el-button>
        <el-button type="primary" @click="finishOrderSubmit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 是否中止采购订单 -->
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible3"
      width="30%"
      @close="dialogFormVisible3 = false">
      您确定中止采购订单?
      <span slot="footer">
        <el-button @click="dialogFormVisible3 = false">取 消</el-button>
        <el-button type="primary" @click="suspendOrderSubmit">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible4"
      width="30%"
      @close="dialogFormVisible4 = false">
      您确定入库?
      <span slot="footer">
        <el-button @click="dialogFormVisible4 = false">取 消</el-button>
        <el-button type="primary" @click="inwarehouseSubmit">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>
<script>
import FileSaver from "file-saver";
import XLSX from "xlsx";
import { mapGetters } from 'vuex';
import {validator} from 'vee-validate'
import {isPhone, isClientName, isManagerName, isClientAff, isShippingAdd, isClientEMail, isInvoiceTitle,
 isFormInvoice, isTelephone, isSalesManager, isOrderPrice, isAdvanceCusName, isNotificationDeli} from '../../validate'

import $ from 'jquery'
// import "../../../node_modules/jquery-table2excel/dist/jquery.table2excel.min"

export default {
    data() {
        return {
            fileUploadBtnText : "后端导入",
            // 实时搜索
            restaurants: [
                // { "value": "天天推" },
                // { "value": "愿意要" },
                // { "value": "大撒打"},
                // { "value": "大撒大撒的", "address": "天山西路438号" },
            ],
            state1: '',
            state2: '',
            // 实时搜索结束 

            totalCount: 0, //分页组件--数据总条数
            list: [],           //表格的数据
            tmpListItem: {      //临时存放list中的一项，用于状态改变传往后台
                purchaseId: "",     //订单ID
                purchaseSubId: "",  //子订单ID（未用）
                purchaseStatus: "", //订单状态
                message: ""         //审批意见
            },
            listLoading: false, //数据加载等待动画
            listQuery: {
                pageNum: 1, //页码
                pageRow: 3, //每页条数
                name: ''
            },
            // 为textMap中的属性,指定标题头
            dialogStatus: 'create',
            dialogFormVisible: false,
            dialogFormVisible1: false,
            dialogFormVisible2: false,
            dialogFormVisible3: false,
            dialogFormVisible4: false,
            radio2: '1',
            textarea2: '',
            textMap: {
                update: '编辑',
                create: '创建采购订单',
                dispalyAtt: '显示字段',
                details: '详情',
                check: '审核',
                finish: '完成',
                suspend: '中止',
                in: '入库'
            },
            tempPurchase: {
                id: "",
                content: ""
            },
            tempObj: {
                id: '',
                value: ''
            },
            delVisible: false, //删除提示弹框的状态
            delVisibleByBatch: false, //批量删除提示弹框的状态
            msg: "", //记录每一条的信息，便于取id
            delarr: [], //存放删除的数据
            multipleSelection: [], //多选的数据
            // 搜索框中的内容
            search: '',
            // 排序的列名
            prop: '',
            // 排序的方式:包括asc,desc等
            order: '',
            // 记录导出得时候跳页的之前的页数
            temp_page: 3,

            // 从后台返回来的数据
            infoFromBack: '',

            displayInfoFromBack: false,

            enableCreate: false,

            multipleSelectionFlag: true,
            // 记录显示字段（初始状态）
            displayAttribute: {
                select:true,
                id:true,                //子订单编号
                purchase_id: true,      //父订单编号（订单号）
                status: true,           //订单状态
                //son_order_id: true,     
                application_id: true,   //申请单号application_id
                supplier_name: true,    //供应商
                supplier_contact: true, //联系人 
                // supplier_phone: false,   //电话 
                // supplier_email: false,   //邮箱 
                // supplier_fax: false,     //传真 
                order_time: true,       //申请日期  
                required_time: true,    //要货日期       
                remark: true,           //备注
                manageMent: true
            },
            purchaseOrder:{
                department_name: "",    //部门（搜索选择）
                staff_name: "",         //发件人（搜索选择）
                staff_name_combine: "", //temp
                supplier_name: "",      //供应商(company)（搜索选择）
                supplier_email: "",     //供应商邮箱
                supplier_fax: "",       //供应商传真
                order_time: "",         //采购订单申请日期
                order_time_tmp: "",
                apply_id: "",           //采购订单申请单号
                purchase_id: "",        //采购订单号
                //purchase_status: "",    //订单状态
                supplier_contact: "",   //供应商联系人
                supplier_phone: "",     //供应商电话
                required_time: "",      //要货时间
                required_time_tmp: "",
                tableDatas: [{
                    product_id: "",     //编号
                    product_name: "",   //货物名称（搜索选择）
                    product_type: "",   //货号
                    quantity: 0,       //数量
                    unit: "",           //单位cc,ml等
                    unit_price: 0.0,     //单价
                    total_price: 0.0,    //总价
                    remark:""           //备注
                }],
                sum: "",                //合计（数据没有字段存储，需实时计算）
                company_id: -1,         //公司ID, -1表示DB未收录，需要先添加，后查ID
                staff_id: -1,           //关联staff表，用staff_name查询ID
                department_id: -1,      //关联department表，用department_name查询ID
                product_id: -1          //关联dim_sc_item表，用product_name查询ID
            },
            staffList2: [],             //暂存所有人员信息
            departmentList2: [],        //暂存所有部门信息
            productList2: [],           //暂存所有货品信息（表dim_sc_item）
            productListQuery: {         //用于获取所有货品
                pageNum: 1, //页码
                pageRow: 5, //每页条数
                value: ""
            },

            //从company.vue拷贝过来
            //保存公司临时信息，用于调用CompanyController接口，存储公司信息；
            tempCompany: {
                id: "",
                company_name: "",
                company_desc: "",
                telephone: "",
                email: "",
                fax: "",
                address: "",
                register_id: "",
                social_credit_code: "",
                taxpayer_identification_number: "",
                organizational_code: ""
            },
            companyList: [],           //暂存DB中所有公司信息


            //添加入库项
            tempInWarehouse:{
                warehousingParentId: "",		//后台自定义P2019MMDDhhmmss
                warehousingSonId: "",			//后台自定义P2019MMDDhhmmss001
                warehousingType: "采购入库",
                warehousingStatus: "待审批",
                
                //以下需要在后天填充所有子订单
                purchaseSonId: "",			    //采购子订单
                goodsId: "",				    //
                unit: "",				        //mm
                storagePutNumOught: 0,         //
                storagePutNum: 0,
                guaranteePeriod: 0,
                //以上需要在后天填充所有子订单

                //warehouseId: "",
                createTime: "0000-00-00 00:00:00",  //
                applicationStaffId: -1, 	    //
                applicationDeptId: -1,		    //

                //以下两项用于更新采购订单状态（同tmpListItem变量）
                purchaseId:"",                  //采购父订单
                purchaseStatus: ""              //采购订单状态
            },

            //不同订单状态显示button的可使用状态
            enableFinishAndSuspend:false,     //完成和中止button
            enableStocking:false,               //入库button
            enableItemShowDetails:false,         //详情
            enableItemEdit:false,                //修改
            enableItemDelete:false,              //删除

            subTableMultipleSelection: [], //多选的数据
            enableDelete:true,
            rules:{
                // order_time_tmp:[
                //     {type: 'date', required: true, message: '请输入申请日期', trigger: 'blur'}
                // ],
                // required_time_tmp:[
                //     {type: 'date', required: true, message: '请输入要货日期', trigger: 'blur'}
                // ]
                // supplier_name:[
                //     {validator: isClientName, trigger: 'blur' }
                // ],
                // manager_name:[
                //     {validator: isManagerName, trigger: 'blur' }
                // ],
                // client_affiliation:[
                //     {validator: isClientAff, trigger: 'blur' }
                // ],
                // shipping_address:[
                //     {validator: isShippingAdd, trigger: 'blur' }
                // ],
                // invoice_title:[
                //     {validator: isInvoiceTitle, trigger: 'blur' }
                // ],
                // form_of_invoice:[
                //     {validator: isFormInvoice, trigger: 'blur' }
                // ],
                // telephone:[
                //     {validator: isTelephone, trigger: 'blur' }
                // ],
                // client_phone:[
                //     {validator: isPhone, trigger: 'blur' }
                // ],
                // client_email:[
                //     {validator: isClientEMail, trigger: 'blur' }
                // ],
                // sales_manager_id:[
                //     {validator: isSalesManager, trigger: 'change' }
                // ],
                // order_price:[
                //     {validator: isOrderPrice, trigger: 'change' }
                // ],
                // advance_customer_name:[
                //     {validator: isAdvanceCusName, trigger: 'change' }
                // ],
                // notification_of_delivery:[
                //     {validator: isNotificationDeli, trigger: 'blur' }
                // ]
            },
            pickerOptions: {
            },
        }
    },
    computed: {
        ...mapGetters([
            'userId',
            'nickname'
        ])
    },
    created() {
        // alert("1");
        this.getList();
        // alert("xxxxxx");
        if (this.hasPerm('company:add') || this.hasPerm('company:update')) {
            this.getAllCompany();
            this.getAllUsers();
            this.getAllDeparments();
            //this.getAllProducts();   //获取表dim_sc_item内容
        }
        if (this.hasPerm('product_order:add') || this.hasPerm('product_order:update')) {
            this.getAllProducts();   //获取表dim_sc_item内容
        }
    },

    mounted() {
        this.getListTest();
    },
    methods: {
        getAllCompany() {
            //获取DB所有公司信息
            this.api({
                url: "/company/listCompany",
                method: "get"
            }).then(data => {
                console.log("allCompany:",data)
                //提供给项目岗位实时搜索
                var json = JSON.parse(JSON.stringify(data.list).replace(/company_name/g,"value"));
                this.companyList = json;
                console.log('companyList:', this.companyList);
            })
        },
        getCompanyId(name) {
            for(var i = 0 ; i < this.companyList.length ; i++){
                if(this.companyList[i]['value'] === name){
                    return this.companyList[i]['company_id'];
                }
            }
            return -1;
        },
        companyQuerySearch(queryString, cb) {
            var tmpLists = this.companyList;
            var results = queryString ? tmpLists.filter(this.createFilter(queryString)) : tmpLists;
            // 调用 callback 返回建议列表的数据
            console.log(results)
            cb(results);
        },
        handleCompanySelect(item) {
            this.purchaseOrder.company_id = item.company_id;
            console.log("select: purchaseOrder.company_id: ", this.purchaseOrder.company_id);
            //this.purchaseOrder.supplier_contact = item.
            this.purchaseOrder.supplier_phone = item.telephone;
            this.purchaseOrder.supplier_email = item.email;
            this.purchaseOrder.supplier_fax = item.fax;
        },    

        //实时搜索输入的内容
        staffQuerySearch(queryString, cb) {
            var staffLists = this.staffList2;
            var results = queryString ? staffLists.filter(this.createFilter(queryString)) : staffLists;
            // 调用 callback 返回建议列表的数据
            console.log(results)
            cb(results);
        },
        handleStaffSelect(item){
            console.log("item", item);
            //所有员工信息在this.staffList中，包括：ID，姓名，部门，岗位
            this.purchaseOrder.staff_name = item.username; 
            this.purchaseOrder.staff_name_combine = item.value;
            this.purchaseOrder.staff_id = item.userId;
        },
        getAllUsers() {
            //获取员工列表
            this.api({
                url: "/user/list",
                method: "get"
            }).then(data => {
                console.log("allUser:",data)
                this.staffList = data.list;
                console.log('user:', this.staffList);

                //提供给实时搜索
                //console.log("data.length: ",data.list.length);
                for(var i = 0 ; i < data.list.length ; i++){
                    var temp = data.list[i];
                    temp['id_nickname'] = data.list[i]['userId']+'-'+data.list[i]['username'];
                    //console.log('temp:', temp);
                    this.staffList2.push(temp);
                }
                //console.log('staffList2:', this.staffList2);
                var json = JSON.parse(JSON.stringify(data.list).replace(/id_nickname/g,"value"));
                this.staffList2 = json;
                console.log('staffList2:', this.staffList2);
            })
        },

        //实时搜索输入的内容（部门）
        departmentQuerySearch(queryString, cb) {
            var departmentList = this.departmentList2;
            var results = queryString ? departmentList.filter(this.createFilter(queryString)) : departmentList;
            // 调用 callback 返回建议列表的数据
            console.log(results)
            cb(results);
        },
        handleDepartmentSelect(item){
            console.log("item", item);
            //所有员工信息在this.staffList中，包括：ID，姓名，部门，岗位
            this.purchaseOrder.department_name = item.value; 
            this.purchaseOrder.department_id = item.department_id;
        },
        getAllDeparments() {
            //获取员工列表
            this.api({
                url: "/department/listDepartment",
                method: "get"
            }).then(data => {
                console.log("AllDeparments:",data)

                //提供给实时搜索
                //console.log('staffList2:', this.staffList2);
                var json = JSON.parse(JSON.stringify(data.list).replace(/department_name/g,"value"));
                this.departmentList2 = json;
                console.log('departmentList2:', this.departmentList2);
            })
        },

        //实时搜索输入的内容（货品）
        productQuerySearch(queryString, cb) {
            var productList = this.productList2;
            var results = queryString ? productList.filter(this.createFilter(queryString)) : productList;
            // 调用 callback 返回建议列表的数据
            console.log(results)
            cb(results);
        },
        handleProductSelect(item, index, row){
            // console.log("index", index);
            // console.log("row", row);
            // console.log("item", item);

            this.purchaseOrder.tableDatas[index].product_id = item.sc_item_id;
            //this.purchaseOrder.tableDatas[index]["product_id"] = item.sc_item_id;
            this.purchaseOrder.tableDatas[index].unit_price = item.sc_item_price;            
        },
        getAllProducts() {
            console.log("get all products");
            //获取员工列表
            this.api({
                url: "/products/listScItem",
                method: "get",
                params: this.productListQuery
            }).then(data => {
                console.log("AllProducts:",data)

                //提供给实时搜索
                var json = JSON.parse(JSON.stringify(data.list).replace(/sc_item_name/g,"value"));
                this.productList2 = json;
                console.log('productList2:', this.productList2);
            })
        },

        // //实时搜索输入的内容（单位）
        // unitQuerySearch(queryString, cb) {
        //     var units = [];
        //     var tmp = { "value": "" };
        //     console.log("this.list: ", this.list.length)
        //     for(let i = 0; i < this.list; i++){ 
        //         tmp["value"] = this.list["unit"];
        //         if (arr.indexOf(tmp) <= -1){
        //             units.push(tmp);
        //         }
        //     }
        //     console.log("units.length: ", units.length)
        //     var results = queryString ? units.filter(this.createFilter(queryString)) : units;
        //     // 调用 callback 返回建议列表的数据
        //     console.log(results)
        //     cb(results);
        // },
        // handleUnitSelect(item){
        //     console.log(item);
        //     //Nothing to do here
        // },

        //计算总价格
        handlerComputeSum(index, row){
            //console.log("index", index);
            //console.log("row", row);

            console.log("触发计算总价格。。。。");
            this.purchaseOrder.tableDatas[index].total_price = row.quantity * row.unit_price;

            //计算表格总价格
            var sum = 0.0;
            console.log("total lines: ", this.purchaseOrder.tableDatas.length);
            for(let i = 0; i < this.purchaseOrder.tableDatas.length; i++){
                console.log("line price: ", index, this.purchaseOrder.tableDatas[i].total_price);
                sum += this.purchaseOrder.tableDatas[i].total_price;
            }
            console.log("order total price: ", sum);
            this.purchaseOrder.sum = sum;
        },





        //添加表格记录
        addRecord(){
            var newLine = {
                product_id:"",
                product_name:"",
                product_type:"",
                quantity:0,
                unit:"",
                unit_price: 0.0,
                total_price: 0.0,
                remark:"",
            };
            this.purchaseOrder.tableDatas.push(newLine);
        },

        subTableHandleSelectionChange(val){
            this.subTableMultipleSelection = val;
            if(this.subTableMultipleSelection.length != 0){
                this.enableDelete = false;
            }else{
                this.enableDelete = true;
            }
        },

        deleteRecord(){
            for(let i = 0; i < this.subTableMultipleSelection.length; i++){
                var index = this.purchaseOrder.tableDatas.indexOf(this.subTableMultipleSelection[i])
                if (index !== -1) {
                this.purchaseOrder.tableDatas.splice(index, 1);
                }
            }
            this.enableDelete = true;
        },

        //转换日期控件时间格式为数据库接受时间格式
        pickerCalendarTime2DbTime(time){
            var d = new Date(time);
            var times=d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
            return times;
        },


        //审核采购订单
        checkOrder(index, row){
            console.log("row：", row);
            console.log('$index:', index);
            if(row.purchaseStatus != "待审核"){
                alert("订单状态错误！");
                return;
            }
            
            this.tmpListItem.purchaseId = row.parentId;
            this.tmpListItem.message = "";
            //this.tmpListItem.purchaseStatus = '采购取消';
            console.log("this.tmpListItem.purchaseId: ", this.tmpListItem.purchaseId);

            this.dialogStatus = "check";
            this.dialogFormVisible1 = true;
        },
        checkOrderSubmit(){
            console.log("this.radio2: ", this.radio2);
            if(this.radio2 == 1){
                this.tmpListItem.purchaseStatus = '审核通过';
            }else{
                this.tmpListItem.purchaseStatus = '审核不通过';
            }            
            this.tmpListItem.message = this.textarea2;
            console.log("this.tmpListItem:", this.tmpListItem);
 
            this.api({
                url: "/purchase/changeStatus",
                method: "post",
                data: this.tmpListItem
            }).then(data => {
                if(this.radio2 == 1){
                    alert("审核通过！", data);
                }else{
                    alert("审核不通过！", data);
                    //this.enableFinishAndSuspend = true;
                } 
                //console.log(data)
                //this.enableItemEdit = true;
                //this.enableItemDelete = true;
                this.dialogFormVisible1 = false;
                this.getList();
            })
        },

	    finishOrder(index, row){
            console.log("row：", row);
            if(row.purchaseStatus != "审核通过"){
                alert("订单状态错误！");
                return;
            }
            this.tmpListItem.purchaseId = row.parentId;
            this.tmpListItem.message = "";

            this.dialogStatus = "finish";
            this.dialogFormVisible2 = true;
        },
        finishOrderSubmit(){
            this.tmpListItem.purchaseStatus = "待入库";
            console.log("tmpListItem:", this.tmpListItem);

            this.api({
                url: "/purchase/changeStatus",
                method: "post",
                data: this.tmpListItem
            }).then(data => {
                // console.log(data)
                this.dialogFormVisible2 = false;
                this.getList();
                alert("订单完成！", data);
            })
        },

        suspendOrder(index, row){
            console.log("row：", row);
            if(row.purchaseStatus != "审核通过"){
                alert("订单状态错误！");
                return;
            }
            this.tmpListItem.purchaseId = row.parentId;
            this.tmpListItem.message = "";

            this.dialogStatus = "suspend";
            this.dialogFormVisible3 = true;
        },
        suspendOrderSubmit(){
            this.tmpListItem.purchaseStatus = "订单中止";
            console.log("tmpListItem:", this.tmpListItem);

            this.api({
                url: "/purchase/changeStatus",
                method: "post",
                data: this.tmpListItem
            }).then(data => {
                // console.log(data)
                this.dialogFormVisible3 = false;
                this.getList();
                alert("订单中止！", data);
            })
        },

        //获取系统当前时间（时间格式yyyy-MM-dd HH:MM:SS）
        setNowFormatDate() {
            let date = new Date();
            let month = (date.getMonth() + 1).toString().padStart(2,'0');
            let strDate = date.getDate().toString().padStart(2,'0');

            return `${date.getFullYear()}-${month}-${strDate} ${this.getCurrentTime()}`;
        },
        getCurrentTime() {
            let date = new Date();
            //时间格式HH:MM:SS
            return `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
        },

        //TODO: 保存入库数据
        inwarehouse(index, row){
            console.log("row：", row);
            if(row.purchaseStatus != "待入库"){
                alert("订单状态错误！");
                return;
            }
            
            this.tmpListItem.purchaseId = row.parentId;     //TO BE Obsolete            
            this.tmpListItem.message = "";                  //TO BE Obsolete


            //New Items
            this.tempInWarehouse.purchaseId = row.parentId; //New
            //添加入库项          
            ////this.tempInWarehouse.warehousingParentId: "";  //后台ServiceImp中自定义P2019MMDDhhmmss
            ////this.tempInWarehouse.warehousingSonId: "";     //后台ServiceImp中自定义P2019MMDDhhmmss001
            //this.tempInWarehouse.purchaseSonId = row.purchaseId; //not used
            //this.tempInWarehouse.goodsId = row.goodsId; //not used
            //this.tempInWarehouse.unit = ;              //TODO
            //this.tempInWarehouse.storagePutNumOught = row.purchaseQuantity; //not used
            //this.tempInWarehouse.storagePutNum = row.purchaseQuantity;  //not used
            //this.tempInWarehouse.guaranteePeriod = ;
            //this.tempInWarehouse.productTime = ;
            this.tempInWarehouse.createTime = this.setNowFormatDate();  //当前时间
            this.tempInWarehouse.applicationStaffId = row.applyStaffId;
            this.tempInWarehouse.applicationDeptId = row.applyDeptId;
            console.log("tempInWarehouse:", this.tempInWarehouse);

            this.dialogStatus = "in";
            this.dialogFormVisible4 = true;
        },
        //TO BE Obsolete   
        inwarehouseSubmit_bak(){
            this.tmpListItem.purchaseStatus = "已入库";
            console.log("tmpListItem:", this.tmpListItem);

            this.api({
                url: "/purchase/changeStatus",
                method: "post",
                data: this.tmpListItem
            }).then(data => {
                // console.log(data)
                this.dialogFormVisible4 = false;
                this.getList();
                alert("订单已申请入库！", data);
            })
        },

        inwarehouseSubmit(){
            //采购订单状态
            this.tempInWarehouse.purchaseStatus = "入库待审批";
            console.log("tempInWarehouse:", this.tempInWarehouse);

            this.api({
                url: "/purchase/addWarehouseEntry",
                method: "post",
                data: this.tempInWarehouse
            }).then(data => {
                // console.log(data)
                this.dialogFormVisible4 = false;
                this.getList();
                alert("订单已入库待审批！", data);
            })
        },




        //上传下载等
        uploadUrl:function(){
            return "/api/excel/importPurchase";
        },
        uploadUrlDingdan:function(){
            return "/api/excel/importDingdan";
        },
        
        handlerPurchase() {
            console.log("content:", this.tempPurchase.content);
            // return;
            this.api({
                url: "/purchase/getPurchaseByContent",
                method: "get",
                params: this.tempPurchase
            }).then(data => {
                console.log("data:", data);
                if (data === "fail") {
                    // alert("无效");
                    this.displayInfoFromBack = true;
                    this.infoFromBack = "无效";
                    this.enableCreate = true;
                } else {
                    this.displayInfoFromBack = false;
                    this.infoFromBack = "";
                    this.enableCreate = false;
                }

            })
        },
        // 获得用户信息
        showUserInfo() {
            console.log('userId:', this.userId);
            console.log('nickname', this.nickname);
        },



        clearFile() {
            this.$refs.clearFile.value = ''; // 清空file文件
        },
        // 导入
        importf(obj) {
            let _this = this;
            let inputDOM = this.$refs.inputer; // 通过DOM取文件数据
            this.file = event.currentTarget.files[0];
            var rABS = false; //是否将文件读取为二进制字符串
            var f = this.file;
            var reader = new FileReader();
            //if (!FileReader.prototype.readAsBinaryString) {
            FileReader.prototype.readAsBinaryString = function(f) {
                var binary = "";
                var rABS = false; //是否将文件读取为二进制字符串
                var pt = this;
                var wb; //读取完成的数据
                var outdata;
                var reader = new FileReader();
                reader.onload = function(e) {
                    var bytes = new Uint8Array(reader.result);
                    var length = bytes.byteLength;
                    for (var i = 0; i < length; i++) {
                        binary += String.fromCharCode(bytes[i]);
                    }
                    var XLSX = require('xlsx');
                    if (rABS) {
                        wb = XLSX.read(btoa(fixdata(binary)), { //手动转化
                            type: 'base64'
                        });
                    } else {
                        wb = XLSX.read(binary, {
                            type: 'binary'
                        });
                    }
                    // outdata就是你想要的东西 excel导入的数据
                    outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
                    // excel 数据再处理
                    let arr = []
                    outdata.map(v => {
                        // console.log(v)
                        let obj = {}
                        obj.content = v.内容
                        obj.id = ""
                        arr.push(obj)
                        _this.tempPurchase = obj
                        console.log(_this.tempPurchase)
                        _this.createPurchase()
                        // this.api({
                        //   url: "/purchase/addPurchase",
                        //   method: "post",
                        //   data: obj
                        // }).then(() => {
                        //   this.getList();
                        //   // this.dialogFormVisible = false
                        // })
                    })
                    _this.accountList = [...arr];
                    console.log(_this.accountList)
                    // _this.reload();
                    // console.log('uuuuuuuuuuuuuuuuuuuuu');
                }
                alert("上传完毕！")
                _this.clearFile()
                reader.readAsArrayBuffer(f);
            }
            if (rABS) {
                reader.readAsArrayBuffer(f);
            } else {
                reader.readAsBinaryString(f);
            }
        },
        // exportPurchase() {
        //     this.api({
        //         url: "/excel/getPurchaseExcel",
        //         method: "get",
        //     }).then(data => {
        //         console.log('getPurchaseExcel:', data)
        //     })
        // },
        // 导入结束

        exportExcelByback() {
            this.api({
                    url: "/excel/exportPurchase",
                    method: "get",
                    
                }).then(() => {
                    // console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
                    alert("导出成功");
                    console.log("导出成功");
                }).catch((err) => {
                    console.log('err:', err);
                    this.$message.error("删除失败")
                })
            // window.location.href= "/excel/exportPurchase";

        },

        exportExcelOpertor() {
            this.temp_page = this.listQuery.pageRow;
            // this.displayAttribute.select = false;
            // this.displayAttribute.manageMent = false;
            console.log(this.totalCount);
            this.handleSizeChange(this.totalCount)
            window.setTimeout(this.exportExcel, 1000);
            window.setTimeout(this.delayTime, 1120);


        },
        
        delayTime() {
            this.listQuery.pageRow = this.temp_page
            // this.displayAttribute.select = true;
            // this.displayAttribute.manageMent = true;
            this.generalFun();
        },
        exportExcel() {
            // alert("exportExcel")
            // 设置当前日期
            let time = new Date();
            let year = time.getFullYear();
            let month = time.getMonth() + 1;
            let day = time.getDate();
            let name = year + "" + month + "" + day;
            this.$nextTick(function() {
                // alert("iiiiiiiiiiiiiiiii");
                // alert(tempPageSize);
                let wb = XLSX.utils.table_to_book(document.querySelector('.tabless'));

                /* get binary string as output */
                let wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' });
                try {
                    FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), name + ".xlsx")
                } catch (e) {
                    if (typeof console !== 'undefined') console.log(e, wbout)
                }
                // this.listQuery.pageRow = 3;//表格还原
                // this.getList();
                return wbout
            })
            // $(".tabless").table2excel({
            //   //需要导出的列
            //   columns:"1,2,3",
            //   // 不被导出的表格行的CSS class类
            //   exclude: ".noExl",
            //   // 导出的Excel文档的名称
            //   name: "Excel",
            //   // Excel文件的名称
            //   filename: "Excel",
            //   // 是否导出图片
            //   exclude_img: true,
            //   // 是否导出超链接
            //   exclude_links: true,
            //   // 是否导出输入框中的内容
            //   exclude_inputs: true
            // });

        },


        inputFunction() {
            // console.log('zandaoguang');
            console.log(this.search);
            console.log(this.search == "");

            if (this.search) {
                // console.log('aaaaaaaaaaaaaaaa');
                this.getListBySearch(this.search);
            }
            if (this.search == "") {
                this.getList();
            }
        },
        sortChange(column, prop, order) {

            // this.handleCurrentChange(1);
            this.listQuery.pageNum = 1;         // 点击排序按钮后拿到column.order，可以发送column.order给后台，后台再根据什么排序来返回排序过后的数据
            // console.log(column);
                     // console.log(column + '---' + column.prop + '---' + column.order)
            // this.prop = column.prop;
            // this.order = column.order;
            // console.log(this.prop);
            // console.log(column.prop);
            // console.log(this.order);
            // 如果搜索框中没有搜索内容
            if (this.search == "") {
                if (column.order === "descending") {
                    this.listQuery.sortby = column.prop;
                    this.listQuery.order = 'DESC';
                    // this.prop = column.prop;
                    // this.order = 'DESC';
                } else {
                    this.listQuery.sortby = column.prop;
                    this.listQuery.order = 'ASC';
                    // this.prop = column.prop;
                    // this.order = 'ASC';
                }
                if (column.prop == "content") {
                    this.getListByOrderContent();
                    // this.prop = '';
                    // this.order = '';
                } else if (column.prop == "createTime") {
                    this.getListByOrderCreateTime();
                    // this.prop = '';
                    // this.order = '';
                } else {
                    // 默认返回id排序
                    this.getList();
                }
            }
            // 如果搜索框中有搜索内容
            else {
                if (column.order === "descending") {
                    this.listQuery.sortby = column.prop;
                    this.listQuery.order = 'DESC';
                    // this.prop = column.prop;
                    // this.order = 'DESC';
                } else {
                    this.listQuery.sortby = column.prop;
                    this.listQuery.order = 'ASC';
                    // this.prop = column.prop;
                    // this.order = 'ASC';
                }
                if (column.prop == "content") {
                    this.getListByContentHaveSearch();
                    // this.prop = '';
                    // this.order = '';
                } else if (column.prop == "createTime") {
                    // 当空格的时候，应该怎么排序
                    // this.getListByOrderCreateTime();
                    // 默认按照id排序
                    // this.getListBySearch(this.search);
                    this.getListByOrderCreateTimeHaveSearch();
                    // this.prop = '';
                    // this.order = '';
                } else {
                    // 默认什么都不做
                    // 默认返回id排序
                    this.getListBySearch(this.search);
                }
            }       //输出的结果 [object Object]---name---ascending
                  
        },
        //单行删除
        handleDelete(index, row) {
            console.log("index:" + index);
            console.log(row);
            this.idx = index;
            this.msg = row; //每一条数据的记录
            console.log("this.msg.PackingId : " + this.msg.PackingId);
            this.delarr.push(this.msg.PackingId); //把单行删除的每条数据的id添加进放删除数据的数组
            console.log("this.delarr : " + this.delarr);
            this.delVisible = true;
        },
        // 当批量删除的时候,如果要是没有选中,弹出提醒
        delWarnInfo() {
            this.$message('请选择您要删除的数据');
        },
        //批量删除
        delAll() {
            // alert("我进来啦~");
            var lengths = this.multipleSelection.length;

            for (let i = 0; i < lengths; i++) {
                // console.log('aaaaaaaaaaaaaaaaaaaaaaaa');
                console.log(this.multipleSelection[i]);
                this.multipleSelection[i].deleteStatus = '2';
                this.api({
                    url: "/purchase/deletePurchase",
                    method: "post",
                    data: this.multipleSelection[i]
                }).then(() => {
                    // console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
                    if (this.search == "") {
                        // alert("我不空啊")
                        this.getList();
                    } else {
                        // alert("我怎么就空了呢？")
                        this.getListBySearch(this.search);
                    }
                }).catch(() => {
                    this.$message.error("删除失败")
                })

            }
            this.delVisibleByBatch = false; //关闭删除提示模态框
        },

        // 确定删除
        deleteRow() {
            let _vue = this;
            // 写自己的删除的对象
            //console.log(this.delarr)
            console.log("_vue.list" + _vue.list);
            console.log("_vue.index:" + _vue.idx);
            let purchase = _vue.list[_vue.idx];
            purchase.purchaseStatus = '采购取消';
            console.log("purchase:", purchase); //子订单ID和订单状态
            _vue.api({
                url: "/purchase/deletePurchase",
                method: "post",
                data: purchase
            }).then(() => {
                console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
                let msg = "删除成功";
                this.dialogFormVisible = false;
                this.$message({
                    message: msg,
                    type: 'success',
                    duration: 1 * 1000,
                    onClose: () => {
                        //this.getList();
                        if(this.search == ""){
                        _vue.getList();
                        }
                        else{
                        // alert("我怎么就空了呢？")
                        _vue.getListBySearch(this.search);
                        }
                    }
                })
            }).catch(() => {
                _vue.$message.error("删除失败")
            })
            this.delVisible = false; //关闭删除提示模态框
        },
        toggleSelection(rows) {
            if (rows) {
                rows.forEach(row => {
                    this.$refs.multipleTable.toggleRowSelection(row);
                });
            } else {
                this.$refs.multipleTable.clearSelection();
            }
        },
        delSelect() {
            const length = this.multipleSelection.length;
            if (length == 0) {
                this.delWarnInfo();
            } else {
                this.delVisibleByBatch = true; //显示删除弹框
            }
            // this.delAll();
        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
            console.log(this.multipleSelection);
        },
        tableRowClassName({ row, rowIndex }) {
            if (rowIndex % 2 === 1) {
                return 'warning-row';
            } else if (rowIndex % 2 === 0) {
                // return 'success-row';
            }
            return '';
        },
        getListTest() {
            //查询列表
            if (!this.hasPerm('article:list')) {
                return
            }
            this.listLoading = true;
            this.api({
                url: "/purchase/listPurchase",
                method: "get",
                params: this.listQuery
            }).then(data => {
                // console.log('我真的帅啊！');
                // console.log("data:",data)
                // return;
                console.log('list:', data.list)
                // 先将json对象转为json字符串，再替换你要替换的属性名，最后再转为json对象
                // console.log('string:', JSON.stringify())
                var json = JSON.parse(JSON.stringify(data.list).replace(/content/g, "value"));
                // console.log("json:",json)
                // for(var i = 0 ; i < data.list.length ; i++){
                // var temp1;
                // console.log('listi:', data.list[i]);
                // console.log('value', data.list[i].content)
                // temp1.value = '';
                // temp1.id = '';
                // console.log('valuessss', this.tempObj.value)
                // console.log('idsssss', this.tempObj.id)
                // this.tempObj.value = data.list[i].content;
                // // console.log('id', data.list[i].id)
                // this.tempObj.id = data.list[i].id;
                //  console.log('valuessss', this.tempObj.value)
                // console.log('idsssss', this.tempObj.id)
                // console.log('tempOb:', this.tempObj);
                // this.restaurants.push(this.tempObj);
                // console.log('restaurants:', this.restaurants)
                // }
                this.restaurants = json;
                // console.log("restaurants:",this.restaurants);
            })
        },
        getList() {
            //查询列表
            if (!this.hasPerm('article:list')) {
                return
            }
            this.listLoading = true;
            this.api({
                url: "/purchase/listPurchase",
                method: "get",
                params: this.listQuery
            }).then(data => {
                console.log('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
                console.log("getList():", data)
                this.listLoading = false;
                this.list = data.list;
                this.tables = data.list;
                this.totalCount = data.totalCount;
            })
        },
        getListByOrderContent() {
            //查询列表

            if (!this.hasPerm('article:list')) {
                return
            }
            this.listLoading = true;
            this.api({
                url: "/purchase/listPurchaseByOrder",
                method: "get",
                params: this.listQuery
            }).then(data => {
                // console.log('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
                // console.log(data)
                this.listLoading = false;
                this.list = data.list;
                this.tables = data.list;
                this.totalCount = data.totalCount;
            })
        },

        // 当搜索框中有内容的时候，排序的时候需要只排序搜索出来的内容
        getListByContentHaveSearch() {
            //查询列表

            if (!this.hasPerm('article:list')) {
                return
            }
            this.listLoading = true;
            this.listQuery.value = this.search;
            this.api({
                url: "/purchase/listPurchaseByContentHaveSearch",
                method: "get",
                params: this.listQuery
            }).then(data => {
                console.log('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
                console.log(data)
                this.listLoading = false;
                this.list = data.list;
                this.tables = data.list;
                this.totalCount = data.totalCount;
            })
        },

        getListByOrderCreateTimeHaveSearch() {
            //查询列表

            if (!this.hasPerm('article:list')) {
                return
            }
            this.listLoading = true;
            this.listQuery.value = this.search;
            this.api({
                url: "/purchase/getListByOrderCreateTimeHaveSearch",
                method: "get",
                params: this.listQuery
            }).then(data => {
                console.log('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
                console.log(data)
                this.listLoading = false;
                this.list = data.list;
                this.tables = data.list;
                this.totalCount = data.totalCount;
            })
        },
        getListByOrderCreateTime() {
            //查询列表

            if (!this.hasPerm('article:list')) {
                return
            }
            this.listLoading = true;
            this.api({
                url: "/purchase/listPurchaseByOrderCreateTime",
                method: "get",
                params: this.listQuery
            }).then(data => {
                console.log('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
                console.log(data)
                this.listLoading = false;
                this.list = data.list;
                this.tables = data.list;
                this.totalCount = data.totalCount;
            })
        },

        getListBySearch(val) {
            console.log("val:"+val);
            //查询列表
            if (!this.hasPerm('article:list')) {
                return
            }
            this.listLoading = true;
            this.listQuery.value = val;
            // console.log(this.listQuery);
            this.api({
                url: "/purchase/listPurchaseBySearch",
                method: "get",
                params: this.listQuery
            }).then(data => {
                // console.log(data)
                this.listLoading = false;
                this.list = data.list;
                this.totalCount = data.totalCount;
            })
        },
        handleSizeChange(val) {
            //改变每页数量
            // alert("handleSizeChange()")
            this.listQuery.pageRow = val
            this.generalFun();
            // this.handleFilter();
        },
        handleCurrentChange(val) {
            //改变页码


            console.log("sortby:", this.listQuery.sortby)
            console.log("order:", this.listQuery.order)
            this.listQuery.pageNum = val
            this.generalFun();

        },
        getIndex($index) {
            //表格序号
            return (this.listQuery.pageNum - 1) * this.listQuery.pageRow + $index + 1
        },
        showCreate() {
            //显示新增对话框
            this.tempPurchase.content = "";
            this.dialogStatus = "create"
            this.dialogFormVisible = true
        },
        showDisplay() {
            this.dialogStatus = "dispalyAtt"
            this.dialogFormVisible = true
        },
        showDetails() {
            this.dialogStatus = "details"
            this.dialogFormVisible = true
        },
        showUpdate($index) {
            //显示修改对话框
            //绑定相应的id
            this.tempPurchase.id = this.list[$index].id;
            //绑定相应的内容
            this.tempPurchase.content = this.list[$index].content;
            this.dialogStatus = "update"
            this.dialogFormVisible = true
        },
        createPurchase_bak() {
            //保存新采购订单
            // console.log(this.tempPurchase)
            // return;
            this.api({
                url: "/article/addPurchase",
                method: "post",
                data: this.tempPurchase
            }).then(() => {
                this.getList();
                this.dialogFormVisible = false
            })
        },

        //保存新公司(供应商)，获取ID
        createCompany() {
            console.log("save company111111111111")
            this.tempCompany.company_name = this.purchaseOrder.supplier_name;
            this.tempCompany.email = this.purchaseOrder.supplier_email;
            this.tempCompany.fax = this.purchaseOrder.supplier_fax; 
            this.tempCompany.telephone = this.purchaseOrder.supplier_phone;

            console.log("save company22222222", this.tempCompany);

            this.api({
                url: "/company/addCompany",
                method: "post",
                data: this.tempCompany
            }).then(() => {
                //console.log("create company finished");
                this.getAllCompany();
                console.log("get all company2222", this.companyList);
                //获取新保存公司的ID
                this.purchaseOrder.company_id = this.getCompanyId(this.purchaseOrder.supplier_name);
                console.log("获取到company_id:", this.purchaseOrder.company_id);
            })
        },

        //创建新订单前，检查公司是否存在DB，若未存在，先添加公司，获取公司ID，然后创建订单
        createPurchase(){
            this.purchaseOrder.company_id = this.getCompanyId(this.purchaseOrder.supplier_name);
            if (this.purchaseOrder.company_id == -1){
                this.createCompany();
                console.log("save new company/supplier firstly");
            }
            console.log("purchaseOrder.company_id:", this.purchaseOrder.company_id);

            //保存新采购订单
            this.purchaseOrder.order_time = this.pickerCalendarTime2DbTime(this.purchaseOrder.order_time_tmp);
            this.purchaseOrder.required_time = this.pickerCalendarTime2DbTime(this.purchaseOrder.required_time_tmp);

            //var lengths = this.purchaseOrder.tableDatas.length;
            console.log("this.purchaseOrder.supplier_contact: ", this.purchaseOrder.supplier_contact);
            console.log(this.purchaseOrder);
            console.log(this.purchaseOrder.tableDatas);

            // if(lengths != 0){
            //     for (let i = 0; i < lengths; i++) {
            //         let obj1 = {}
            //         let obj2 = {}
            //         let obj3 = {}
            //         obj1 = this.chemicals.find((item) => {
            //         return item.value === this.tempOrder.tableDatas[i].chemical_modification;
            //         });
            //         obj2 = this.flus.find((item) => {
            //             return item.value === this.tempOrder.tableDatas[i].flu_labeling;
            //         });
            //         obj3 = this.specials.find((item) => {
            //             return item.value === this.tempOrder.tableDatas[i].special_modi;
            //         });

            //         if(obj1 != null){
            //             this.tempOrder.tableDatas[i].chemical_modification = obj1.label
            //         }
            //         if(obj2 != null){
            //             this.tempOrder.tableDatas[i].flu_labeling = obj2.label
            //         }
            //         if(obj3 != null){
            //             this.tempOrder.tableDatas[i].special_modi = obj3.label
            //         }
            //     }
            // }

            this.$refs.dynamicValidateOligo.validate((valid) => {
                if (valid) {
                    this.api({
                    url: "/purchase/addPurchase",
                    method: "post",
                    data: this.purchaseOrder
                    }).then(() => {
                        let msg = "采购订单添加成功";
                        this.dialogFormVisible = false;
                        this.$message({
                            message: msg,
                            type: 'success',
                            duration: 1 * 1000,
                            onClose: () => {
                            this.getList();
                            }
                        })

                        //alert("添加采购订单完成！")
                        //this.getList();
                        //this.dialogFormVisible = false
                        //this.resetForm('dynamicValidateOligo')
                    })
                } else {
                    alert("请输入完整的信息！");
                }
            });
        },



        updatePurchase() {
            console.log("tempPurchase:" + this.tempPurchase);
            //修改采购订单
            this.api({
                url: "/purchase/updatePurchase",
                method: "post",
                data: this.tempPurchase
            }).then(() => {
                this.getList();
                this.dialogFormVisible = false
            })
        },

        generalFun() {
            this.getListTest();
            if (this.search) {
                if (this.listQuery.sortby == "" & this.listQuery.order == "") {

                    this.getListBySearch(this.search);
                } else if (this.listQuery.sortby == "content" && this.listQuery.order == "ASC") {
                    // alert("你好啊")
                    // this.listQuery.sortby = this.prop;
                    // this.listQuery.order = "ASC";
                    this.getListByContentHaveSearch();
                } else if (this.listQuery.sortby == "content" && this.listQuery.order == "DESC") {
                    // alert("很好啊")
                    // this.listQuery.sortby = this.prop;
                    // this.listQuery.order = "DESC";
                    this.getListByContentHaveSearch();
                } else if (this.listQuery.sortby == "createTime" && this.listQuery.order == "ASC") {
                    // this.listQuery.sortby = this.prop;
                    // this.listQuery.order = "ASC";
                    this.getListByOrderCreateTimeHaveSearch();
                } else if (this.listQuery.sortby == "createTime" && this.listQuery.order == "DESC") {
                    // this.listQuery.sortby = this.prop;
                    // this.listQuery.order = "DESC";
                    this.getListByOrderCreateTimeHaveSearch();
                } else {
                    // alert("xxxxxx");
                    this.getListBySearch(this.search);
                    // ...
                }
            }
            // 没有搜索内容，所以可以直接
            else {
                // alert("ssssssssssssssssss")
                // console.log(this.prop);
                // console.log(this.order);
                if (this.listQuery.sortby == "" & this.listQuery.order == "") {

                    this.getList();
                } else if (this.listQuery.sortby == "content" && this.listQuery.order == "ASC") {
                    // this.listQuery.sortby = this.prop;
                    // this.listQuery.order = "ASC";
                    // ...
                    this.getListByOrderContent();
                } else if (this.listQuery.sortby == "content" && this.listQuery.order == "DESC") {
                    // this.listQuery.sortby = this.prop;
                    // this.listQuery.order = "DESC";
                    this.getListByOrderContent();
                } else if (this.listQuery.sortby == "createTime" && this.listQuery.order == "ASC") {
                    // this.listQuery.sortby = this.prop;
                    // this.listQuery.order = "ASC";
                    this.getListByOrderCreateTime();
                } else if (this.listQuery.sortby == "createTime" && this.listQuery.order == "DESC") {
                    // this.listQuery.sortby = this.prop;
                    // this.listQuery.order = "DESC";
                    this.getListByOrderCreateTime();
                } else {
                    // ...
                    this.getList();
                    // alert("我是空的！")
                }
            }
        },
        loadAll() {
            return [
                { "value": "三全鲜食（北新泾店）", "address": "长宁区新渔路144号" },
                { "value": "Hot honey 首尔炸鸡（仙霞路）", "address": "上海市长宁区淞虹路661号" },
                { "value": "新旺角茶餐厅", "address": "上海市普陀区真北路988号创邑金沙谷6号楼113" },
                { "value": "泷千家(天山西路店)", "address": "天山西路438号" },
                { "value": "胖仙女纸杯蛋糕（上海凌空店）", "address": "上海市长宁区金钟路968号1幢18号楼一层商铺18-101" },
                { "value": "贡茶", "address": "上海市长宁区金钟路633号" },
                { "value": "豪大大香鸡排超级奶爸", "address": "上海市嘉定区曹安公路曹安路1685号" },
                { "value": "茶芝兰（奶茶，手抓饼）", "address": "上海市普陀区同普路1435号" },
                { "value": "十二泷町", "address": "上海市北翟路1444弄81号B幢-107" },
                { "value": "星移浓缩咖啡", "address": "上海市嘉定区新郁路817号" },
                { "value": "阿姨奶茶/豪大大", "address": "嘉定区曹安路1611号" },
                { "value": "新麦甜四季甜品炸鸡", "address": "嘉定区曹安公路2383弄55号" },
                { "value": "Monica摩托主题咖啡店", "address": "嘉定区江桥镇曹安公路2409号1F，2383弄62号1F" },
                { "value": "浮生若茶（凌空soho店）", "address": "上海长宁区金钟路968号9号楼地下一层" },
                { "value": "NONO JUICE  鲜榨果汁", "address": "上海市长宁区天山西路119号" },
                { "value": "CoCo都可(北新泾店）", "address": "上海市长宁区仙霞西路" },
                { "value": "快乐柠檬（神州智慧店）", "address": "上海市长宁区天山西路567号1层R117号店铺" },
                { "value": "Merci Paul cafe", "address": "上海市普陀区光复西路丹巴路28弄6号楼819" },
                { "value": "猫山王（西郊百联店）", "address": "上海市长宁区仙霞西路88号第一层G05-F01-1-306" },
                { "value": "枪会山", "address": "上海市普陀区棕榈路" },
                { "value": "纵食", "address": "元丰天山花园(东门) 双流路267号" },
                { "value": "钱记", "address": "上海市长宁区天山西路" },
                { "value": "壹杯加", "address": "上海市长宁区通协路" },
                { "value": "唦哇嘀咖", "address": "上海市长宁区新泾镇金钟路999号2幢（B幢）第01层第1-02A单元" },
                { "value": "爱茜茜里(西郊百联)", "address": "长宁区仙霞西路88号1305室" },
                { "value": "爱茜茜里(近铁广场)", "address": "上海市普陀区真北路818号近铁城市广场北区地下二楼N-B2-O2-C商铺" },
                { "value": "鲜果榨汁（金沙江路和美广店）", "address": "普陀区金沙江路2239号金沙和美广场B1-10-6" },
                { "value": "开心丽果（缤谷店）", "address": "上海市长宁区威宁路天山路341号" },
                { "value": "超级鸡车（丰庄路店）", "address": "上海市嘉定区丰庄路240号" },
                { "value": "妙生活果园（北新泾店）", "address": "长宁区新渔路144号" },
                { "value": "香宜度麻辣香锅", "address": "长宁区淞虹路148号" },
                { "value": "凡仔汉堡（老真北路店）", "address": "上海市普陀区老真北路160号" },
                { "value": "港式小铺", "address": "上海市长宁区金钟路968号15楼15-105室" },
                { "value": "蜀香源麻辣香锅（剑河路店）", "address": "剑河路443-1" },
                { "value": "北京饺子馆", "address": "长宁区北新泾街道天山西路490-1号" },
                { "value": "饭典*新简餐（凌空SOHO店）", "address": "上海市长宁区金钟路968号9号楼地下一层9-83室" },
                { "value": "焦耳·川式快餐（金钟路店）", "address": "上海市金钟路633号地下一层甲部" },
                { "value": "动力鸡车", "address": "长宁区仙霞西路299弄3号101B" },
                { "value": "浏阳蒸菜", "address": "天山西路430号" },
                { "value": "四海游龙（天山西路店）", "address": "上海市长宁区天山西路" },
                { "value": "樱花食堂（凌空店）", "address": "上海市长宁区金钟路968号15楼15-105室" },
                { "value": "壹分米客家传统调制米粉(天山店)", "address": "天山西路428号" },
                { "value": "福荣祥烧腊（平溪路店）", "address": "上海市长宁区协和路福泉路255弄57-73号" },
                { "value": "速记黄焖鸡米饭", "address": "上海市长宁区北新泾街道金钟路180号1层01号摊位" },
                { "value": "红辣椒麻辣烫", "address": "上海市长宁区天山西路492号" },
                { "value": "(小杨生煎)西郊百联餐厅", "address": "长宁区仙霞西路88号百联2楼" },
                { "value": "阳阳麻辣烫", "address": "天山西路389号" },
                { "value": "南拳妈妈龙虾盖浇饭", "address": "普陀区金沙江路1699号鑫乐惠美食广场A13" }
            ];
        },
        querySearch(queryString, cb) {
            var restaurants = this.restaurants;
            var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
            // 调用 callback 返回建议列表的数据
            cb(results);
        },
        createFilter(queryString) {
            return (restaurant) => {
                return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
            };
        },
        handleSelect(item) {
            console.log(item);
        },
        fileUploadSuccess(response, file, fileList){
            alert("上传成功");
            this.generalFun();
            console.log('res:', response);
            console.log('file:', file);
            console.log('fileList:', fileList);
        },
        fileUploadError(err, file, fileList){
            alert("上传失败");
            console.log('err:', err);
            console.log('file:', file);
            console.log("fileList:" , fileList);
        },
        beforeFileUpload(file){
            // alert("上传之前:" , file);
            console.log('file:', file);

        }
    }

}
</script>


<style>
.el-table .warning-row {
    background: whitesmoke;
    /* background: #ffffff; */
}

.el-table .success-row {
    background: #f0f9eb;
}

.pagination {
    background-color: lavender;
    margin-right: 0%;
    text-align: right;
}

.searchWord .add1 {
    display: inline;
}

#btn {
    /* padding: 5px 10px;
            background: #00b0f0;
            color: #FFF;
            border: none;
            border-radius: 5px; */
}
</style>